package com.itheima.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.Emtity.Category;
import com.itheima.common.R;
import com.itheima.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    @PostMapping()
    public R<String> save(@RequestBody Category category) {
        log.info(category.toString());
        categoryService.save(category);
        return R.success("新增分类成功");
    }


    @GetMapping("page")
    public R<Page> page(int page, int pageSize) {
        log.info("page=" + page, "pageSize=" + pageSize);

//        1.构造分页构造器
        Page<Category> objectPage = new Page<>(page, pageSize);

//        需要分页构造器   2. 和where.
        LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.orderByAsc(Category::getSort);
        categoryService.page(objectPage, lambdaQueryWrapper);

        return R.success(objectPage);
    }

    /**
     * 根据id删除分类
     *
     * @param ids
     * @return
     */
    @DeleteMapping()
    public R<String> deleteID(long ids) {
        boolean remove = categoryService.remove(ids);
        if (remove) {
            return R.success("删除成功");
        } else {
            return R.success("删除失败");
        }
    }

    /**
     * 根据id修改数据
     *
     * @param category
     * @return
     */
    @PutMapping()
    public R<String> update(@RequestBody Category category) {
        boolean b = categoryService.updateById(category);
        return R.success("修改成功");
    }


    /***
     *  获得下拉框的数据.
     *  前端传送的是type字段.
     * @param category
     * @return
     */

    @GetMapping("list")
//    参数用类,不要用具体的字段,否则后面有什么增加的的麻烦
//    为什么用实体类?
    // 请求的数据是  1. 要从category表里面拿的,    2. where参数  判断也是category表里面的.    所以接收参数是Category

    // 通过这个可以获得菜品和套餐.字段一样,只是字段的值不一样.
    //处理同样的字段
    public R<List<Category>> list(Category category) {
        LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        categoryLambdaQueryWrapper.eq(category.getType() != null, Category::getType, category.getType());
        categoryLambdaQueryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
//        返回
        List<Category> list = categoryService.list(categoryLambdaQueryWrapper);
        return R.success(list);
    }
}
